package org.dftproject.lineagelinkage.ui;

import org.dftproject.genesis.core.tasks.ITask;
import org.dftproject.genesis.core.tasks.TaskManager;
import org.dftproject.genesis.data.genealogy.IPerson;
import org.dftproject.lineagelinkage.core.DuplicateManager;
import org.dftproject.lineagelinkage.core.IDuplicateManagerListener;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;

public class Activator extends AbstractUIPlugin {

	public static final String ID = "org.dftproject.lineagelinkage.ui";

	public static final String RESOLVE_DUPLICATES_TASK = "org.dftproject.lineagelinkage.tasks.resolveDuplicates";
	
	private static Activator plugin;

	@Override
	public void start(BundleContext context) throws Exception {
		super.start(context);
		plugin = this;
		
		DuplicateManager.getDefault().addListener(new IDuplicateManagerListener() {
			
			private final Object lock = new Object();

			public void duplicateAdded(IPerson person, IPerson duplicate) {
				long count = DuplicateManager.getDefault().getDuplicateCount();
				if (count > 0) {
					TaskManager taskManager = TaskManager.getDefault();
					synchronized (lock) {
						ITask task = taskManager.getTask(RESOLVE_DUPLICATES_TASK);
						if (task == null) {
							taskManager.addTask(new ResolveDuplicatesTask(RESOLVE_DUPLICATES_TASK, count));
						} else if (task instanceof ResolveDuplicatesTask) {
							((ResolveDuplicatesTask) task).setCount(count);
							taskManager.updateTask(task);
						}
					}
				}
			}

			public void duplicateRemoved(IPerson person, IPerson duplicate) {
				long count = DuplicateManager.getDefault().getDuplicateCount();
				if (count == 0) {
					TaskManager taskManager = TaskManager.getDefault();
					synchronized (lock) {
						ITask task = taskManager.getTask(RESOLVE_DUPLICATES_TASK);
						if (task != null)
							TaskManager.getDefault().removeTask(task);
					}
				} else {
					TaskManager taskManager = TaskManager.getDefault();
					synchronized (lock) {
						ITask task = taskManager.getTask(RESOLVE_DUPLICATES_TASK);
						if (task == null) {
							taskManager.addTask(new ResolveDuplicatesTask(RESOLVE_DUPLICATES_TASK, count));
						} else if (task instanceof ResolveDuplicatesTask) {
							((ResolveDuplicatesTask) task).setCount(count);
							taskManager.updateTask(task);
						}
					}
				}
			}
			
		});
		
		long count = DuplicateManager.getDefault().getDuplicateCount();
		if (count > 0)
			TaskManager.getDefault().addTask(new ResolveDuplicatesTask(RESOLVE_DUPLICATES_TASK, count));
	}

	@Override
	public void stop(BundleContext context) throws Exception {
		plugin = null;
		super.stop(context);
	}

	public static Activator getDefault() {
		return plugin;
	}

	public static ImageDescriptor getImageDescriptor(String path) {
		return imageDescriptorFromPlugin(ID, path);
	}

}
